<template>
  <div class="my-posts">
    <!-- 页面标题 -->
    <div class="page-header">
      <button class="back-button" @click="goBack">
        <i class="icon-back"></i>
      </button>
      <h1 class="page-title">我的发帖</h1>
      <div class="placeholder"></div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="posts.length === 0" class="empty-state">
      <div class="empty-icon">📝</div>
      <p class="empty-text">还没有发帖</p>
      <p class="empty-hint">快去发表你的第一篇帖子吧</p>
    </div>

    <!-- 帖子列表 -->
    <div v-else class="posts-list">
      <div 
        v-for="post in posts" 
        :key="post.id" 
        class="post-item"
        @click="goToPost(post)"
      >
        <div class="post-header">
          <span class="post-time">{{ formatTime(post.createTime) }}</span>
          <span v-if="post.isEssence" class="post-badge essence">精华</span>
        </div>
        
        <h3 class="post-title">{{ post.title }}</h3>
        
        <div class="post-content">
          {{ post.content }}
        </div>

        <!-- 帖子图片 -->
        <div v-if="post.imageList && post.imageList.length > 0" class="post-images">
          <img 
            v-for="(image, index) in post.imageList.slice(0, 3)" 
            :key="index" 
            :src="image" 
            class="post-image"
            alt="帖子图片"
          >
          <div v-if="post.imageList.length > 3" class="more-images">
            +{{ post.imageList.length - 3 }}
          </div>
        </div>

        <div class="post-footer">
          <div class="post-stats">
            <span class="stat-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M12 2C12 2 5 8 5 13C5 17.4183 8.58172 21 13 21C17.4183 21 21 17.4183 21 13C21 9 17 6 17 6C17 6 17 8 15 8C15 8 14 4 12 2Z" 
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
              </svg>
              {{ post.viewCount || 0 }}
            </span>
            <span class="stat-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"
                  stroke="currentColor" stroke-width="2" />
              </svg>
              {{ post.likeCount || 0 }}
            </span>
            <span class="stat-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" stroke="currentColor" stroke-width="2" />
              </svg>
              {{ post.commentCount || 0 }}
            </span>
          </div>
          <button class="delete-btn" @click.stop="deletePost(post)">
            删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getPostPage, deleteForumPost } from '@/api/forum'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(true)
const posts = ref([])

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  
  const date = new Date(timeString)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于1天
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 小于7天
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  
  // 超过7天显示具体日期
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 跳转到帖子详情
const goToPost = (post) => {
  router.push(`/forum/post/${post.id}`)
}

// 获取帖子列表
const fetchPosts = async () => {
  if (!userStore.uid) {
    console.error('用户未登录')
    router.push('/user/login')
    return
  }

  loading.value = true
  try {
    const res = await getPostPage({
      userId: userStore.uid,
      pageNum: 1,
      pageSize: 100
    })
    
    if (res.code === 200 && res.data) {
      posts.value = res.data.list || []
    } else {
      console.error('获取帖子列表失败:', res.msg)
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除帖子
const deletePost = async (post) => {
  if (!confirm('确定要删除这篇帖子吗？删除后无法恢复！')) {
    return
  }

  try {
    const res = await deleteForumPost(post.id)
    console.log('删除帖子成功:', res)

    if (res.code === 200) {
      // 删除成功后，重新获取帖子列表
      await fetchPosts()
      alert('帖子已删除')
    } else {
      alert('删除失败：' + (res.message || res.msg || '未知错误'))
    }
  } catch (error) {
    console.error('删除帖子失败:', error)
    alert('删除帖子失败，请稍后重试')
  }
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.my-posts {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 页面标题 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-button {
  width: 36px;
  height: 36px;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #f0f2f5;
}

.icon-back::before {
  content: '←';
  font-size: 1.5rem;
  color: #1976d2;
}

.page-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.placeholder {
  width: 36px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1976d2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #9ca3af;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 1.1rem;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #6b7280;
}

.empty-hint {
  font-size: 0.9rem;
  margin: 0;
}

/* 帖子列表 */
.posts-list {
  padding: 16px;
}

.post-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-item:hover {
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.15);
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.post-time {
  font-size: 0.85rem;
  color: #9ca3af;
}

.post-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.post-badge.essence {
  background: linear-gradient(135deg, #fff3e0, #ffe0b2);
  color: #f57c00;
}

.post-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-content {
  font-size: 0.9rem;
  line-height: 1.6;
  color: #6b7280;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 帖子图片 */
.post-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  position: relative;
}

.post-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.more-images {
  position: absolute;
  right: 8px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.post-stats {
  display: flex;
  gap: 20px;
}

.delete-btn {
  background: none;
  border: none;
  color: #ff4757;
  cursor: pointer;
  font-size: 0.85rem;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.delete-btn:hover {
  background: #fff5f5;
  color: #d63031;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 0.85rem;
  color: #9ca3af;
}

.stat-item svg {
  color: #9ca3af;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .page-header {
    padding: 12px 16px;
  }

  .page-title {
    font-size: 1.1rem;
  }

  .posts-list {
    padding: 12px;
  }

  .post-item {
    padding: 14px;
  }

  .post-title {
    font-size: 1rem;
  }

  .post-images {
    gap: 6px;
  }

  .post-image {
    width: 70px;
    height: 70px;
  }
}
</style>
